import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { mediaListService, mediaSearchService } from '@/apis/media.js'

export const useMediaStore = defineStore('media', () => {
  const medias = ref([])
  const pageNum = ref(1)
  const total = ref(0)
  const pageSize = ref(21)
  const search = ref('')
  const allMedias = ref([])

  const filteredMedias = computed(() => {
    if (search.value) {
      return medias.value.filter(media =>
        media.title.toLowerCase().includes(search.value.toLowerCase())
      )
    }
    return medias.value
  })

  async function fetchMedias() {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    let result
    if (search.value) {
      result = await mediaSearchService({ ...params, query: search.value })
    } else {
      result = await mediaListService(params)
    }
    total.value = result.data.total
    medias.value = result.data.items

    // // Process category names
    // // 
    // medias.value.forEach(article => {
    //   const category = categorys.value.find(c => c.id === article.categoryId)
    //   if (category) {
    //     article.categoryName = category.categoryName
    //     article.articleCount = category.articleCount
    //   }
    // })
  }

  async function fetchAllMedias() {
    // 设置一个大的pageSize，一次性获取所有文章
    const result = await mediaListService({ pageSize: 1000, pageNum: 1 }) // Fetch a large number of articles
    // 按时间排序
    allmedias.value = result.data.items.sort((a, b) =>
      new Date(b.createTime) - new Date(a.createTime)
    )
  }

  function onSizeChange(size) {
    pageSize.value = size
    fetchMedias()
  }

  function onCurrentChange(num) {
    pageNum.value = num
    fetchMedias()
  }

  return {
    medias,
    pageNum,
    total,
    pageSize,
    search,
    filteredMedias,
    fetchMedias,
    onSizeChange,
    onCurrentChange,
    allMedias,
    fetchAllMedias
  }
})

